package enterprise.web.tookit.integration.email;

import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import enterprise.web.tookit.email.Email;
import enterprise.web.tookit.email.EmailBeanRemote;

/**
 * Session Bean implementation class EmailBean
 */
@Stateless(mappedName = "ejb/EmailBean")
public class EmailBean implements EmailBeanRemote {

	@Resource(mappedName = "topic/emailService")
	private Topic topic;

	@Resource(mappedName = "ConnectionFactory")
	private TopicConnectionFactory topicFactory;

	/**
	 * Persistence Context enterprisewebtoolkit_db
	 */
	@PersistenceContext(unitName = "enterprisewebtoolkit")
	private EntityManager enterpriseWebToolkitDb;

	/**
	 * LOG
	 */
	private final static Logger log = Logger.getLogger(EmailBean.class);

	/**
	 * Default constructor.
	 */
	public EmailBean() {
	}

	@Override
	public boolean sendEmail(final Email email) {

		try {
			final TopicConnection connection = topicFactory.createTopicConnection();

			connection.start();

			final TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

			final TopicPublisher publisher = session.createPublisher(topic);

			final MapMessage message = session.createMapMessage();

			message.setString("nome", "Regis");
			message.setInt("idade", 23);

			publisher.send(message);

			// close resources
			publisher.close();
			session.close();
			connection.close();
		} catch (JMSException e) {
			log.error("", e);
		} catch (Exception e) {
			log.error("", e);
		}

		return true;
	}

	@Override
	public void saveEmail(final Email email) {
		final EmailDao dao = new EmailDao(enterpriseWebToolkitDb);

		try {
			dao.persist(email);
		} catch (Exception e) {
			log.error("", e);
			throw new EJBException(e);
		}
	}

	@Override
	public Email updateEmail(Email email) {
		final EmailDao dao = new EmailDao(enterpriseWebToolkitDb);

		try {
			email = dao.merge(email);
		} catch (Exception e) {
			log.error("", e);
			throw new EJBException(e);
		}

		return email;
	}

	@Override
	public void deleteEmail(final Email email) {
		final EmailDao dao = new EmailDao(enterpriseWebToolkitDb);

		try {
			dao.remove(email);
		} catch (Exception e) {
			log.error("", e);
			throw new EJBException(e);
		}
	}

	@Override
	public Email obterConfiguracaoEmail() {
		final EmailDao dao = new EmailDao(enterpriseWebToolkitDb);

		try {
			return dao.obterConfiguracaoEmail();
		} catch (Exception e) {
			log.error("", e);
			throw new EJBException(e);
		}
	}
}
